<template>
  <div id="market_gameticket_ticketbag">
    <div class="search-box">
      <Row type="flex" justify="space-between">
        <Row type="flex">
          <Col class="search-item"><span class="search-label">名称：</span><Input placeholder="请输入" @on-keyup='filterSpace' v-model='searchName'></Input></Col>
          <Col class="search-item">
            <span class="search-label">门店：</span>
            <Select v-model="shopType"
              class="select-shop-item"
              multiple
              filterable
              :max-tag-count="1"
              :max-tag-placeholder="maxTagPlaceholder"
              style="width:180px">
              <Option v-for="item in shopList" :value="item.shopId" :key="item.shopId">{{ item.shopName }}</Option>
            </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">价格：</span>
            <Select v-model="priceType"
              class="select-shop-item"
              multiple
              :max-tag-count="1"
              :max-tag-placeholder="maxTagPlaceholder"
              style="width:180px">
              <Option v-for="(item, index) in priceList" :value="item.configCode" :key="index">{{ item.configValue }}</Option>
            </Select>
          </Col>
          <!-- <Col id='subcard-first'>
            <Row type="flex" justify="start">
              <Col class="search-item">
                <span class="search-label">局数：</span>
                  <Select v-model="selectedType" style="width:180px">
                    <Option v-for="item in selectedList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
              </Col>
              <Col class="search-item">
                <span class="search-label">状态：</span>
                  <Select v-model="selectedType" style="width:180px">
                    <Option v-for="item in selectedList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                  </Select>
              </Col>
            </Row>
          </Col> -->
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="search"
                  >查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
            @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             style="padding-right:16px">
          <Col>
            <div id="btn-export">
              <Row type="flex" style='padding-right:20px'>
                <Col class="search-item"><Button class="search-btn" type="primary" @click="skipAdd" v-if="hasPermission('moms:market:createpackagegamecoupon')">新增</Button></Col>
              </Row>
            </div>
          </Col>
          <Col class="search-item">
            <Button v-if="exampleShow"
                  @click="exampleShow = !exampleShow">收起筛选
              <Icon type="ios-arrow-up" />
            </Button>
            <Button v-else
                    @click="exampleShow = !exampleShow">更多筛选
              <Icon type="ios-arrow-down" />
            </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example"
           v-show="exampleShow">
        <Row type="flex" justify="start">
          <Col class="search-item">
            <span class="search-label">局数：</span>
              <Select v-model="timesType"
                class="select-shop-item"
                multiple
                :max-tag-count="1"
                :max-tag-placeholder="maxTagPlaceholder"
                style="width:180px">
                <Option v-for="(item, index) in timesList" :value="item.configCode" :key="index">{{ item.configValue }}</Option>
              </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">状态：</span>
              <Select v-model="selectedType" style="width:180px">
                <Option v-for="item in selectedList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
          </Col>
          <Col class="search-item">
            <span class="search-label">销售形式：</span>
              <Select v-model="salesType" style="width:180px">
                <Option v-for="item in salesTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
          </Col>
        </Row>
      </div>
      <div id="btn-export-show">
        <Row type="flex"
             justify="end"
             style="width:100%;padding-right:16px">
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  v-if="hasPermission('moms:market:createpackagegamecoupon')"
                  @click="skipAdd">新增</Button>
          </Col>
        </Row>
      </div>
    </div>
    <Table stripe class="table-list" :columns="columns" :data="data" :height="this.tableHeight" :loading="loading">
      <template slot-scope="{ row, index }" slot="status">
        <span>{{ getEnumsName(row.status, selectedList) }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="salesType">
        <span>{{ getEnumsName(row.salesType, salesTypes) }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="salesChannel">
        <span>{{ (row.salesChannelName || []).join('/') }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="buyLimit">
        <span>{{ row.timeUnitLimit ? row.buyLimit + '/' + getEnumsName(row.timeUnitLimit, timeUnitLimits) : getEnumsName(row.timeUnitLimit, timeUnitLimits) }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="listingTime">
        <span>{{ formatTime(row.listingTime) }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="delistingTime">
        <span>{{ formatTime(row.delistingTime) }}</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <i class="iconsys icondetail" title="查看详情" @click='skipDetail(row, index)' v-if="hasPermission('moms:market:detailpackagegamecoupon')"></i>
        <i class="iconsys iconedit" @click="skipEdit(row,index)" title="编辑" v-if="hasPermission('moms:market:updatepackagegamecoupon') && row.status == 0"></i>
        <Poptip transfer confirm title="你确定要删除吗？" @on-ok="sureDel(row, index)" class="poptip_del" v-if="hasPermission('moms:market:deletepackagegamecoupon') && row.status == 0">
          <i class="iconsys icondel" title="删除"></i>
        </Poptip>
        <i class="iconsys iconshenhe" title="审核" @click='audit(row)' style='font-size:21px' v-if="hasPermission('moms:market:auditpackagegamecoupon') && row.status == 0"></i>
        <Poptip transfer confirm title="你确定要下架吗？" @on-ok="soldOut(row, index)" class="poptip_del" v-if="hasPermission('moms:market:delistpackagegamecoupon') && row.status == 3 && row.salesType != 2">
          <i class="iconsys iconxiajia" title="下架"></i>
        </Poptip>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
        <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <Modal v-model="modalShow" :title="modalTitle" :transfer='false' @on-ok="sureAudio" class-name="vertical-center-modal">
      <RadioGroup v-model="pass" style='padding:15px 0'>
        <Radio label="1" style="margin-left:20px">审核通过</Radio>
        <Radio label="0" style="margin-left:120px">审核未通过</Radio>
      </RadioGroup>
    </Modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getShopList } from '@/api/system/store'
// import { getPriceLists } from '@/api/market/game-ticket/priceTimes.js'
import { getPriceLists } from '@/api/market/game-ticket-old/priceTimes.js'
import { getSubcardLists, reviewSubcard, deleteSubcard, pullOffSubcard } from '@/api/market/game-ticket/subcardTicketbag.js'
import enumsMixin from '../enums'
export default {
  name: 'market_gameticket_ticketbag',
  mixins: [enumsMixin],
  data () {
    return {
      searchName: '',
      exampleShow: false,
      pass: '1',
      modalShow: false,
      modalTitle: '审核',
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      loading: false,
      tableHeight: 0,
      shopType: '',
      shopList: [],
      priceType: '',
      priceList: [],
      timesType: '',
      timesList: [],
      selectedType: '-1',
      salesType: -1,
      salesTypes: [
        { label: '全部', value: -1 },
        { label: '单独销售', value: 1 },
        { label: '打包销售', value: 2 }
      ],
      columns: [
        {
          title: '编号',
          key: 'gameCouponCode',
          width: 150,
          fixed: 'left'
        },
        {
          title: '门店',
          key: 'shopName',
          minWidth: 150
        },
        {
          title: '销售渠道',
          slot: 'salesChannel',
          minWidth: 150
        },
        {
          title: '名称',
          key: 'name',
          minWidth: 150
        },
        {
          title: '价格',
          key: 'price',
          minWidth: 100
        },
        {
          title: '局数',
          key: 'round',
          width: 100
        },
        {
          title: '销售形式',
          slot: 'salesType',
          width: 120
        },
        {
          title: '购买数量限制(份)',
          slot: 'buyLimit',
          width: 130
        },
        {
          title: '有效期',
          key: 'validPeriod',
          width: 220
        },
        {
          title: '状态',
          slot: 'status',
          width: 100
        },
        {
          title: '上架时间',
          slot: 'listingTime',
          width: 150
        },
        {
          title: '下架时间',
          slot: 'delistingTime',
          width: 150
        }
      ],
      data: []
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_gameticket_ticketbag') {
        this.search()
      }
      const poptips = document.querySelectorAll('body .ivu-poptip-popper.ivu-poptip-confirm.v-transfer-dom')
      poptips.forEach(poptip => {
        if (poptip.style.display !== 'none') poptip.style.display = 'none'
      })
    }
  },
  mounted () {
    this.getSelects()
    this.getData()
    if (this.hasPermission(['moms:market:detailpackagegamecoupon', 'moms:market:auditpackagegamecoupon', 'moms:market:delistpackagegamecoupon', 'moms:market:updatepackagegamecoupon', 'moms:market:deletepackagegamecoupon'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 210,
        fixed: 'right'
      })
    }
  },
  methods: {
    maxTagPlaceholder (num) {
      return '...'
    },
    getSelects () {
      getShopList({
        permissionCode: 'moms:market:viewpackagegamecouponlist',
        merchantId: this.merchantId,
        offset: 0,
        limit: 9999
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.shopList = result.data || []
        }
      })
      this.getPriceOrTimes(1).then(result => {
        this.priceList = result
      })
      this.getPriceOrTimes(2).then(result => {
        this.timesList = result
      })
    },
    getPriceOrTimes (type) {
      return new Promise(resolve => {
        getPriceLists({
          merchantId: this.merchantId,
          configType: type
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            resolve(result.data || [])
          }
        })
      })
    },
    filterSpace () {
      this.searchName = this.searchName.replace(/\s+/g, '')
    },
    skipAdd () {
      this.$router.push({ name: 'market_gameticket_ticketbag_create' })
    },
    skipEdit (row) {
      this.$router.push({
        name: 'market_gameticket_ticketbag_edit',
        query: {
          id: row.gameCouponCode,
          trueId: row.id,
          shopId: row.shopId
        }
      })
    },
    skipDetail (row) {
      this.$router.push({
        name: 'market_gameticket_ticketbag_detail',
        query: {
          id: row.gameCouponCode,
          shopId: row.shopId
        }
      })
    },
    sureDel (row) {
      deleteSubcard({
        shopId: row.shopId,
        id: row.id
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('删除成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    soldOut (row) {
      pullOffSubcard({
        shopId: row.shopId,
        id: row.id
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('下架成功！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    audit (row) {
      this.audioRow = row
      this.modalShow = true
    },
    sureAudio () {
      reviewSubcard({
        shopId: this.audioRow.shopId,
        id: this.audioRow.id,
        isApproved: this.pass === '1'
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.$Message.success('审核完成！')
          this.getData()
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    getData () {
      this.loading = true
      this.tableHeight = 0
      getSubcardLists({
        merchantId: this.merchantId,
        name: this.searchName,
        shopIds: this.shopType || [],
        priceCodes: this.priceType || [],
        roundCodes: this.timesType || [],
        status: this.selectedType === '-1' ? '' : +this.selectedType,
        salesType: this.salesType === -1 ? '' : this.salesType,
        type: 2,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = result.data || []
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    reset () {
      this.searchName = ''
      this.shopType = ''
      this.priceType = ''
      this.timesType = ''
      this.selectedType = '-1'
      this.salesType = -1
      this.search()
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    }
  }
}
</script>

<style lang='less'>
  #market_gameticket_ticketbag{
    .vertical-center-modal{
      display: flex;
      align-items: center;
      justify-content: center;
      .ivu-modal{
          top: 0;
      }
    }
    .ivu-table-tip {
      span {
        position: absolute;
        width: 100px;
        left: 50%;
        margin-left: -50px;
      }
    }
    .ivu-btn-text {
      border-color: #DCDEE2;
    }
    .ivu-btn-large {
      width: 72px;
    }
    .select-shop-item {
      height: 35px;
      width: 210px;
      .ivu-select-selection {
        height: 35px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .ivu-tag {
        max-width: 100px;
      }
    }
    .select-shop-item .ivu-select-dropdown {
      width: 300px;
    }
    .select-shop-item .ivu-select-item {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .select-shop-item .ivu-select-input {
      width: 40px !important;
    }
  }
</style>
